import hashlib
import requests
import re
import time


def get_m_h5_tk_value(s):
    # 定义正则表达式模式
    pattern = r'_m_h5_tk=([^_]+)'

    # 使用 re.search 查找匹配
    match = re.search(pattern, s)

    # 如果找到匹配，返回匹配的值
    if match:
        return match.group(1)
    else:
        return None

def generate_sign(t: str, token: str, data: str) -> str:
    """生成签名，参考获取商品信息接口的签名生成方式"""
    app_key = "34839810"
    msg = f"{token}&{t}&{app_key}&{data}"
    
    # 使用MD5生成签名
    md5_hash = hashlib.md5()
    md5_hash.update(msg.encode('utf-8'))
    return md5_hash.hexdigest()


def get_xy_user_nick(Cookie):
    dict_data = '{}'
    token = get_m_h5_tk_value(Cookie)
    timestamp = int(time.time() * 1000)
    
    # 使用与获取商品信息接口相同的签名生成方式
    sign = generate_sign(str(timestamp), token, dict_data)
    
    payload='data=%7B%7D'
    url = f"https://h5api.m.goofish.com/h5/mtop.idle.web.user.page.nav/1.0/?jsv=2.7.2&appKey=34839810&t={timestamp}&sign={sign}&v=1.0&type=originaljson&accountSite=xianyu&dataType=json&timeout=20000&api=mtop.idle.web.user.page.nav&sessionOption=AutoLoginOnly&spm_cnt=a21ybx.personal.0.0&spm_pre=a21ybx.home.nav.1.4c053da6zJQWYv&log_id=4c053da6zJQWYv"
    headers = {
       'accept': 'application/json',
       'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
       'origin': 'https://www.goofish.com',
       'priority': 'u=1, i',
       'referer': 'https://www.goofish.com/',
       'sec-ch-ua': '"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"',
       'sec-ch-ua-mobile': '?0',
       'sec-ch-ua-platform': '"Windows"',
       'sec-fetch-dest': 'empty',
       'sec-fetch-mode': 'cors',
       'sec-fetch-site': 'same-site',
       'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0',
       'Cookie': Cookie,
       'content-type': 'application/x-www-form-urlencoded',
       'Host': 'h5api.m.goofish.com',
       'Connection': 'keep-alive'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    try:
        displayName = response.json()['data']['module']['base']['displayName']
    except:
        displayName = None
    return displayName